package com.springboot.manager.config.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.springboot.manager.common.CommonResult;
import com.springboot.manager.entity.User;
import com.springboot.manager.enums.SSOCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @version v1.0
 * @ProjectName: hlk-microservice-ails
 * @ClassName: TokenInterceptor
 * @Description: TODO(一句话描述该类的功能)
 * @Author: zhangzl
 * @Date: 2021-07-30 15:23
 */
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    public final String REDIS_TOKEN_KEYWORD = "token";

    @Value("${spring.redis.keyword}")
    public String KEYWORD;

    @Value("${interceptor.token}")
    public boolean interceptorToken;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) {

        if (interceptorToken) {
            String methodType = request.getMethod();
            String tokenValue = "";

            if (RequestMethod.POST.name().equals(methodType) || RequestMethod.OPTIONS.name().equals(methodType)) {
                tokenValue = request.getHeader("token");
            } else if (RequestMethod.GET.name().equals(methodType)) {
                tokenValue = request.getParameter("token");
            }

            if (StrUtil.isNotBlank(tokenValue)) {
                User user = JSONObject.parseObject(JSONObject.toJSONString(redisTemplate.opsForValue().get(KEYWORD + ":" + REDIS_TOKEN_KEYWORD + ":" + tokenValue)), User.class);
                /*User user = (User) redisUtil.get(REDIS_TOKEN_KEYWORD + tokenValue);*/
                if (ObjectUtil.isNull(user)) {
                    writeBackInfo(response);
                    return false;
                }
            } else {
                writeBackInfo(response);
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }

    private void writeBackInfo(HttpServletResponse response) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            new CommonResult<>(SSOCodeEnum.NO_LOGIN.getCode(), SSOCodeEnum.NO_LOGIN.getMsg());
            String error = "token信息有误";
            writer.print(new CommonResult<>(SSOCodeEnum.NO_LOGIN.getCode(), SSOCodeEnum.NO_LOGIN.getMsg()));
        } catch (IOException e) {
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

}
